import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '../stores/auth'

const routes = [
  {
    path: '/',
    redirect: to => {
      const token = localStorage.getItem('token')
      if (!token) {
        return { path: '/login' }
      }
      return { path: '/dashboard' }
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/DataDashboard.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/devices',
    name: 'Devices',
    component: () => import('../views/Devices.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/statistics',
    name: 'Statistics',
    component: () => import('../views/Statistics.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/batches',
    name: 'Batches',
    component: () => import('../views/Batches.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/employees',
    name: 'Employees',
    component: () => import('../views/EmployeeManagement.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/users',
    name: 'Users',
    component: () => import('../views/UserManagement.vue'),
    meta: {
      requiresAuth: true,
      requiredRole: 'admin'
    }
  },
  {
    path: '/roles',
    name: 'Roles',
    component: () => import('../views/RoleManagement.vue'),
    meta: {
      requiresAuth: true,
      requiredRole: 'admin'
    }
  },
  {
    path: '/icon-test',
    name: 'IconTest',
    component: () => import('../views/IconTest.vue'),
    meta: { requiresAuth: false }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth !== false)
  const requiredRole = to.matched.find(record => record.meta.requiredRole)?.meta.requiredRole

  if (to.path === '/login' && authStore.isAuthenticated) {
    next({ path: '/dashboard' })
    return
  }

  if (requiresAuth && !authStore.isAuthenticated) {
    next({ name: 'Login', query: { redirect: to.fullPath } })
    return
  }

  if (requiredRole && !authStore.hasRole(requiredRole)) {
    console.log('用户角色检查失败:', {
      userRoles: authStore.userRoles,
      requiredRole,
      hasRole: authStore.hasRole(requiredRole)
    })
    ElMessage.error('没有访问权限')
    next({ path: '/dashboard' })
    return
  }

  console.log('路由守卫通过，允许访问:', to.path)
  next()
})

export default router






